const app = getApp()
const request = require('../../utils/https.js')
import util from '../../utils/util.js';
var userId, height;
var context = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    iconUrl: 'https://osskm.km3830.cn/kmzx/share/2020/3/6-221243-538BJjjr.png',
    invite_girl:'https://oss.km3830.cn/pic/zx/invite_girl.png?'+((new Date()).getTime()),
    authorize:false,
    loading: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    userId = wx.getStorageSync('userId');
    let userInfo = wx.getStorageSync('userInfo'); //用户信息

    that.getGoods(userInfo);
    //获取头像
    if (userId) {
      console.log('有userid')
      //获取微信头像请求后台接口返回文件流 用于canvas 图片素材 用户头像

      if (userInfo.avatarUrl && userInfo.avatarUrl != '' && userInfo.avatarUrl != undefined && userInfo.avatarUrl != 'undefined' && userInfo.avatarUrl != null) {
        console.log('头像有效')
        var avatarUrl = userInfo.avatarUrl
        wx.downloadFile({
          url: getApp().Api_url + 'user/downloadIcon?pics=' + avatarUrl,
          success(res) {
            // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
            if (res.statusCode == 200) {
              console.log('=res.tempFilePath==>', res.tempFilePath)
              wx.getImageInfo({
                src: res.tempFilePath,
                success: function (res) {
                  console.log('==src====>', res.path)
                  that.data.iconUrl = res.path;
                }
              })
            }
          }
        })
      } else {
        console.log('头像无有效')
        //更新用户信息
        wx.getUserInfo({
          success: function (res) {
            console.log('调取头像')
            var avatarUrl = res.userInfo.avatarUrl

            console.log('avatarUrl==>', avatarUrl)
            wx.downloadFile({
              url: getApp().Api_url + 'user/downloadIcon?pics=' + avatarUrl,
              success(res) {
                // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                if (res.statusCode == 200) {
                  console.log('=res.tempFilePath==>', res.tempFilePath)
                  wx.getImageInfo({
                    src: res.tempFilePath,
                    success: function (res) {
                      console.log('==src====>', res.path)
                      that.data.iconUrl = res.path;
                    }
                  })
                }
              }
            })

          }
        })
      }
    }
  },
  //loading图详情
  getGoods(userInfo) {
    const that = this;

    that.setData({
      dynamicContent: userInfo.nickName //绘标题文字
    })
    that.getCode()
    //第一张图片设置高宽
    wx.getImageInfo({
      src: 'https://oss.km3830.cn/pic/zx/invite_boy2.jpg',
      success: function (res) {
        console.log(res.path)
        that.data.amongImg = res.path
        console.log('第一张图片的信息')
        var Width = res.width, //获取第一张图片真实宽度
          Height = res.height,
          ratio = Width / Height; //图片的真实宽高比例

            //设置图片显示宽度
        var drawWidth = 1500;
        var drawHeight = 2154; //计算的高度值

        that.setData({
          loading:false,
          drawWidth: drawWidth, //第一张图的绘图宽度
          drawHeight: drawHeight //第一张图的绘图高度
        })
      }
    })
  },


  //获取小程序码图片并转码
  getCode() {
    const that = this;
    request._get(getApp().Api_url + 'user/share', {
      userId: userId
    }, function (res) {
      if (res.data.errMsg == 'OK') {
        //获取网络图片本地路径生成canvas 图片素材 二维码
        wx.getImageInfo({
          src: res.data.data,
          success: function (res) {
            console.log('二维码===>', res.path)
            that.data.ewmUrl = res.path;
          }
        })
      }
    }, function () {})

    //获取网络图片本地路径生成canvas 图片素材 二维码
    wx.getImageInfo({
      src: that.data.ewmUrl,
      success: function (res) {
        console.log(res.path)
        that.data.ewmUrl = res.path;
      }
    })
  },

  //用canvas绘制图片
  saveQRcode: function (e) {
    let that = this;
    let userId = wx.getStorageSync("userId");

    wx.showLoading({
      title: '努力绘制中～',
    })
    // 设置画板显示，才能开始绘图
    context = wx.createCanvasContext('qrcode');
    context.setFillStyle("white")
    context.stroke();
    // 设置背景图
    var path = "../../images/white-bg.png"; //白色背景
    var logoUrl = that.data.ewmUrl; //二维码

    that.setData({ //画板高度
      canvasH: 500 + that.data.drawHeight
    })

    //var reg = /[\u4e00-\u9fa5]/g;
    //var names = that.data.dynamicContent.match(reg);
    //var textTie = 'aumo' + names.join(""); //商品名字描述


    //var arrLength = Math.ceil(textTie.length / 17);
    //处理发帖内容文字部分
    //var aa = '';
    //var j = 0; //记录行数
    //var k = 0;

    /* for (var i = 0; i < textTie.length; i++) {
      var enterStr = textTie.substring(i, i + 1);
      aa += enterStr;
      k++;
      console.log('enterStr==>', enterStr);
      if ((k % 17) == 0 || i == textTie.length || enterStr == "\n") {
        j++;
        var titleAa = util.toThousands(aa);
        aa = '';
        k = 0;
      }
    } */

    //画完帖子内容部分之后的高度
    //var drawHeightSucessHei = that.data.drawHeight + 240 + (40 * (j + 1));
    //画板总共的高度
    //var allHeight = (that.data.canvasH) + (40 * (j - 1));

    var allHeight = that.data.canvasH;

    context.drawImage(path, 0, 0, 1500, allHeight); //白板背景
    context.drawImage(logoUrl, 139, that.data.drawHeight + 75, 356, 356) //二维码
    context.drawImage(that.data.amongImg, 0, 0, that.data.drawWidth, that.data.drawHeight); //(帖子图片详情图片)

    // 添加标题

    //var title1 = util.toThousands(' 我在 "快美帽饰aumo" 欣赏到一件');
    //var title2 = util.toThousands(' 时尚礼物，让我们一起拥有“她”');
    // var title3 = util.toThousands('长按图片立即购买');
    var title3 = util.toThousands('长按小程序码了解更多');
    // var title4 = util.toThousands('邀请好友还可以获赠KM，抵扣现金');
    var title4 = util.toThousands('邀请好友还可获赠美颜值，抵扣现金');
    var names = that.data.dynamicContent;

    //绘制商品名字
    //that.drawWord();


    //绘制文字内容部分
    //1
    /*     context.setFontSize(24);
        context.setFillStyle("#333");
        context.fillText(title1, 120, 65);
        context.stroke(); */
    //2
    /*     context.setFontSize(24);
        context.setFillStyle("#333");
        context.fillText(title2, 120, 105);
        context.stroke(); */
    //3
    context.setFontSize(76);
    context.setFillStyle("#000");
    context.fillText(title3, 572, that.data.drawHeight + 215,750);
    context.stroke();
    //4
    context.setFontSize(48);
    context.setFillStyle("#B4B3BA");
    context.fillText(title4, 572, that.data.drawHeight + 320,750);
    context.stroke();

    //names
    context.setFontSize(58);
    context.setFillStyle("#3C3835");
    let metrics = context.measureText(names)
    let betweenPoint = parseInt((1500-146-metrics.width)/2);
    let namePoint = betweenPoint+146;
    context.fillText(names, namePoint, 450);
    context.stroke();


    //context.drawImage('../../images/ait.png', 80, 55, 240, 39) //喜欢就买她png图片

    //截切头像圆形区域 sta
    context.beginPath(); //开始绘制
    //先画个圆   前两个参数确定了圆心 （x,y） 坐标  第三个参数是圆的半径  四参数是绘图方向  默认是false，即顺时针
    // context.arc(203, 160, 18, 0, Math.PI * 2, false);
    context.arc(betweenPoint+54, 426, 54, 0, Math.PI * 2, false);

    context.clip(); //画好了圆 剪切  原始画布中剪切任意形状和尺寸。一旦剪切了某个区域，则所有之后的绘图都会被限制在被剪切的区域内 这也是我们要save上下文的原因

    context.drawImage(that.data.iconUrl, betweenPoint, 372, 108, 108); //上角icon  logo,头像
    context.restore(); //恢复之前保存的绘图上下文 恢复之前保存的绘图上下午即状态 还可以继续绘制
    //截切头像圆形区域 end

    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    context.draw(true, setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'qrcode',
        success: function (res) {
          var tempFilePath = res.tempFilePath;
          console.info(tempFilePath)
          that.setData({
            imagePath: tempFilePath
          });
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: function () {
              wx.saveImageToPhotosAlbum({
                filePath: tempFilePath,
                success: function (res) {
                  setTimeout(function () {
                    wx.hideLoading()
                    that.setData({
                      showWeal: false,
                      fixed: 'fixed',
                      isImg: true
                    })
                    wx.showToast({
                      title: '已保存到相册',
                      icon: 'success',
                      duration: 700
                    })
                  }, 1200)

                },
                fail: function (res) {
                  console.log('禁止保存到相册')

                  wx.hideLoading()
                  that.setData({
                    showWeal: false,
                    fixed: '',

                  })
                }
              })
            },
            fail: function (res) {
              console.log('拒绝授权=======>')
              wx.hideLoading()
              that.setData({
                showWeal: false,
                fixed: 'fixed',
                authorize: true
              })
              
            }
          })

        },
        fail: function (res) {
          console.log(res);
        }
      });
    }, 500))
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    const that = this;
    userId = wx.getStorageSync("userId");

    if (userId == '' || userId == null || userId == 'undefined') {
      wx.reLaunch({
        url: '/pages/login/login?path=/pages/yqhy/yqhy',
      })
      return;
    } else {
      if (res.from === 'button') {
        // 来自页面内转发按钮
        console.log('来自页面内转发按钮 userId===>', userId)
        return {
          title: '快美甄选',
          path: '/pages/list/list?userId=' + userId,
          imageUrl:that.data.iconUrl
        }
      } else {
        console.log('非按钮转发 userId===>', userId)
        return {
          title: '快美甄选',
          path: '/pages/list/list?userId=' + userId,
          imageUrl:that.data.iconUrl
        }
      }

    }
  },
  shutToast(){
    const that=this;
    that.setData({
      authorize:false
    })
  },
  onAuthorize(){
    const that = this;
    that.setData({
      authorize:false
    })
  }
})